package com.sun.module_mine.ui.pinlock

import androidx.biometric.BiometricPrompt
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.sun.module_base.ext.showToast
import com.sun.module_base.widget.HorizontalDottedProgressBar
import com.sun.module_mine.utils.BiometricUtils

/**
 *@author:sunc
 *@time :2025/8/14 13:43
 *@desc: 描述 指纹验证
 */
@Composable
fun FingerprintAuthScreen(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val isLoading = remember { mutableStateOf(false) }


    fun launchAuth() {
        val promptInfo = BiometricPrompt.PromptInfo.Builder()
            .setTitle("身份验证")
            .setSubtitle("请按压指纹传感器")
            .setNegativeButtonText("取消")
            .build()

        val biometricPrompt = BiometricPrompt(
            (context as FragmentActivity),
            ContextCompat.getMainExecutor(context),
            object :
                BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                    showToast("验证成功")
                    isLoading.value = false
                }

                override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                    showToast("验证失败：$errString")
                    isLoading.value = false
                }
            })
        biometricPrompt.authenticate(promptInfo)
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .background(color = MaterialTheme.colorScheme.onPrimary)
            .padding(bottom = 48.dp),
        verticalArrangement = Arrangement.Bottom,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        if (BiometricUtils.isBiometricReady(context)) {
            Button(onClick = {
                isLoading.value = true
                launchAuth()
            }) {
                if (isLoading.value) {
                    HorizontalDottedProgressBar()
                } else {
                    Text("开始指纹验证")
                }
            }
        } else {
            Text("设备不支持指纹功能", color = MaterialTheme.colorScheme.error)
        }
    }
}